﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RookieLibSharp.Configuration;
using System.IO;
using RookieLibSharp.Progress;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XSSF;

namespace BirthdayRemainder.Forms
{
    public partial class FrmExportData : Form
    {
        private string FilePath;
        private const int THD_ID = 0;
        private const string PROGRESS_TITLE = "导出数据";
        /// <summary>
        /// 是否导出成功
        /// </summary>
        private bool ExportSuccess = false;
        /// <summary>
        /// 是否点击了浏览按钮
        /// </summary>
        private bool ClickOpenFile = false;

        string[] ArrTitle = new string[] { "序号", "姓名", "生日", "阳历/阴历", "手机号码" };

        public FrmExportData()
        {
            InitializeComponent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿|*.xls|文本文档(*.txt)|*.txt";
            sfd.FileName = "data";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                this.tbFilePath.Text = sfd.FileName;
                ClickOpenFile = true;
            }
        }

        private void tbFilePath_TextChanged(object sender, EventArgs e)
        {
            Cfg.WriteConfig(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_EXPORT_FILE_PATH, ((TextBox)sender).Text);
        }

        private void FrmExportData_Load(object sender, EventArgs e)
        {
            this.tbFilePath.Text = Cfg.ReadString(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_EXPORT_FILE_PATH);
        }

        private void btnExportData_Click(object sender, EventArgs e)
        {
            FilePath = this.tbFilePath.Text;
            if (!ClickOpenFile && File.Exists(FilePath))
            {
                if (Msg("文件存在，是否覆盖?",MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
            }
            ExportSuccess = false;
            ProgressManager.StartThread(ExportData);
            if (ExportSuccess)
            {
                Msg("导出成功");
                CloseFrm();
            }

        }
        private void ExportData()
        {
            ProgressManager.UpdateStringInfo(PROGRESS_TITLE);
            try
            {
                if (Path.GetExtension(FilePath).ToLower() == ".txt")
                {
                    ExportSuccess = ExportToTxt(FilePath);
                }
                else
                {
                    ExportSuccess = ExportToExcel(FilePath);
                }
            }
            catch
            {
                ExportSuccess = false;
            }

            ProgressManager.CloseProcessFrm();
        }
        private bool ExportToTxt(string filePath)
        {
            List<PersonInfo> LstInfo = SftMgr.DbGetAllInfo();
            if (LstInfo.Count == 0)
            {
                Msg("没有数据可以导出");
                return false;
            }
            using (FileStream FS = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                ProgressManager.Init(THD_ID, PROGRESS_TITLE,LstInfo.Count);
                StreamWriter sw = new StreamWriter(FS,Encoding.Default);
                string str = "";
                for (int idx = 0; idx < ArrTitle.Length;idx++ )
                {
                    str += ArrTitle[idx] + ",";
                }
                sw.WriteLine(str.Substring(0, str.Length - 1));
                for (int idx = 0; idx < LstInfo.Count; idx++)
                {
                    str = LstInfo[idx].GetSaveStr();
                    sw.WriteLine(string.Format("{0},{1}", idx + 1, str));
                    ProgressManager.UpdateVale(THD_ID);
                }
                sw.Close();
                FS.Close();
            }
            return true;
        }
        private bool ExportToExcel(string filePath)
        {
            if (Funcs.IsFileInUse(filePath))
            {
                Msg("该文件已经被打开，请关闭相关软件");
                return false;
            }
            List<PersonInfo> LstInfo = SftMgr.DbGetAllInfo();
            if (LstInfo.Count == 0)
            {
                Msg("没有数据可以导出");
                return false;
            }
            ProgressManager.Init(THD_ID, PROGRESS_TITLE, LstInfo.Count + ArrTitle.Length);
            int nRow = 0,nCol;
            IWorkbook wkBk;
            if (Path.GetExtension(filePath) == ".xls")
            {
                wkBk = new HSSFWorkbook();
            }
            else
            {
                wkBk = new XSSFWorkbook();
            }
            ISheet wkSht = wkBk.CreateSheet("数据"+DateTime.Now.ToString("HHmmss"));
            IRow row = wkSht.CreateRow(nRow++);
            ICell cell;
            for (int idx = 0; idx < ArrTitle.Length; idx++)
            {
                cell = row.CreateCell(idx);
                cell.SetCellValue(ArrTitle[idx]);
                ProgressManager.UpdateVale(THD_ID);
            }
            for (int idx = 0; idx < LstInfo.Count; idx++)
            {
                nCol = 0;
                row = wkSht.CreateRow(nRow++);
                cell = row.CreateCell(nCol++);
                cell.SetCellValue(idx+1);
                cell = row.CreateCell(nCol++);
                cell.SetCellValue(LstInfo[idx].Name);
                cell = row.CreateCell(nCol++);
                cell.SetCellValue(LstInfo[idx].Birthday);
                cell = row.CreateCell(nCol++);
                cell.SetCellValue(LstInfo[idx].SolorOrLunar);
                cell = row.CreateCell(nCol++);
                cell.SetCellValue(LstInfo[idx].Phone);
                ProgressManager.UpdateVale(THD_ID);
            }
            using (FileStream file = new FileStream(filePath, FileMode.Create))
            {
                wkBk.Write(file);
                file.Close();
            }
            return true;
        }
        /// <summary>
        /// 关闭窗口委托
        /// </summary>
        private delegate void dl_CloseFrm();
        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void CloseFrm()
        {
            if (this.InvokeRequired)
            {
                dl_CloseFrm method = CloseFrm;
                Invoke(method);
                return;
            }
            this.Close();
        }
        private delegate DialogResult dl_Msg(string str, MessageBoxButtons btn);
        /// <summary>
        /// 消息显示
        /// </summary>
        /// <param name="str">消息内容</param>
        /// <param name="btn">按钮类型</param>
        /// <returns>消息窗体结果</returns>
        private DialogResult Msg(string str, MessageBoxButtons btn = MessageBoxButtons.OK)
        {
            if (this.InvokeRequired)
            {
                dl_Msg method = Msg;
                return (DialogResult)Invoke(method, str, btn);
            }
            return MessageBox.Show(str, "提醒", btn);
        }
    }
}
